#include "citycodeutils.h"

#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QDebug>
#include <QJsonObject>
#include <QJsonValue>


CityCodeUtils::CityCodeUtils()
{

}

void CityCodeUtils::initCityMap()
{
    //打开文件 获取字节数组
    QFile file("g:/QtProjectfile/citycode.json");
    if(file.open(QIODevice::ReadOnly)==true)
    {
        qDebug()<<"文件打开成功"<<endl;
    }
    QByteArray rawData = file.readAll();
    file.close();

    //将字节数组转换为json文档
    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    //创建文档数组
    QJsonArray citys = jsonDoc.array();
    //定义一个数组内的对象
    QJsonObject citysArrObject;
    //定义一个指向QJsonArray类数组成员的迭代器
    QJsonArray::iterator it;
    for ( it = citys.begin();it !=citys.end() ;it++ )
    {
        citysArrObject = (*it).toObject();
        //打印城市名
        QJsonValue value_cityName = citysArrObject.value("city_name");
        QString cityName = value_cityName.toString();
        //打印城市代码
        QJsonValue value_cityCode = citysArrObject.value("city_code");
        QString cityCode = value_cityCode.toString();
        //插入到映射中
        cityMap.insert(cityName,cityCode);
    }

}

QString CityCodeUtils::getCityCodeFromName(QString cityName)
{
    //判空 if映射为空 初始化映射
    if(cityMap.isEmpty()){
        initCityMap();
    }
    //定义一个迭代器 初值为传入的城市名
    QMap<QString, QString>::iterator it = cityMap.find(cityName);
    if( it == cityMap.end()){
        it = cityMap.find(cityName+"市");
        if(it == cityMap.end()){
            it = cityMap.find(cityName+"县");
        }
        if(it == cityMap.end()){
            it = cityMap.find(cityName+"区");
        }
        if(it == cityMap.end()){
            return "";
        }
    }
    return it.value();

}
